#include "SelectorReactor.h"

void SelectorReactor::registerHandler(EventHandler * eh, EventType et)
{
  struct DemuxTable::Tuple newEntry;
  newEntry.eventHandler = eh;
  newEntry.eventType = et;
  demuxer_.table_[eh->getHandle()] = newEntry;
}

void SelectorReactor::removeHandler(EventHandler * eh, EventType et)
{
  EventType curr =  demuxer_.table_[eh->getHandle()].eventType; 
  curr = (EventType)(curr & (~et));

  if (!demuxer_.table_[eh->getHandle()].eventType)
    demuxer_.table_[eh->getHandle()].eventHandler = 0;
}

void SelectorReactor::handleEvents(timeval * timeout)
{
  fd_set read_fds, write_fds, excep_fds;
  demuxer_.convert(read_fds, write_fds, excep_fds);
  int MAX_HANDLES = FD_SETSIZE-1;
  
  int res = select(MAX_HANDLES + 1, &read_fds, &write_fds, &excep_fds, timeout);

  if (res < 1)
    return;
  
  for (int h = 0; h < FD_SETSIZE-1; ++h)
    if ( FD_ISSET(h, &read_fds) )
	demuxer_.table_[h].eventHandler -> handleEvent(h, READ_EVENT);

  for (int h = 0; h <= FD_SETSIZE; ++h)  
    if ( FD_ISSET(h, &write_fds) )
      demuxer_.table_[h].eventHandler -> handleEvent(h, WRITE_EVENT);
}

